/*
    This source file is part of GeNa project.
    Copyright © GeNa project 2008
    For the latest info, see http://code.google.com/p/genaproject/ or  http://lumpyproject.forums-rpg.com

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Foobar is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Foobar.  If not, see <http://www.gnu.org/licenses/>. */

#include "entity.h"
#include "mesh.h"
#include "effect.h"

#include <dom/domInstance_geometry.h>
#include <dom/domGeometry.h>
#include <string>

Entity::Entity(domInstance_geometry* instance)
{
    mesh = new Mesh(((domGeometry*)instance->getUrl().getElement().cast())->getMesh());

    domBind_materialRef dBindMaterial = instance->getBind_material();
    domInstance_material_Array & dInstanceMaterialArray = dBindMaterial->getTechnique_common()->getInstance_material_array();

    for( unsigned int i=0; i < dInstanceMaterialArray.getCount(); i++)
    {
        domInstance_materialRef dInstanceMaterial = dInstanceMaterialArray[i];

        BindMaterial* bindMaterial = new BindMaterial;
        bindMaterial->material = new Material((domMaterial*)dInstanceMaterial->getTarget().getElement().cast());

        materials[dInstanceMaterial->getSymbol()] = bindMaterial;

        domInstance_material::domBind_vertex_input_Array array = dInstanceMaterial->getBind_vertex_input_array();

        for( unsigned int j=0; j < array.getCount(); j++)
            bindMaterial->attributeBinds.push_back( std::pair<std::string, std::string>( array[j]->getInput_semantic(), array[j]->getSemantic()));
    }
}

void Entity::draw()
{
    for( std::list<SubMesh*>::iterator iter = mesh->m_subMeshes.begin(); iter != mesh->m_subMeshes.end(); iter++)
    {
        SubMesh* subMesh = *iter;
        BindMaterial* bMat = materials[subMesh->materialName];

        bMat->material->setupMaterial();
        std::vector<Pass*> & passes = bMat->material->getPasses();

        for( unsigned int i=0; i < passes.size(); i++)
        {
            passes[i]->setupPass();

            for( std::list< std::pair<std::string, std::string> >::iterator iter2 = bMat->attributeBinds.begin(); iter2 != bMat->attributeBinds.end(); iter2++)
                subMesh->linkAttribute(passes[i]->getAttribLocation(iter2->second), iter2->first);

            subMesh->draw();

            passes[i]->cleanPass();

        }

        bMat->material->cleanMaterial();
    }

}
